﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;

namespace SatisAktarim
{
    public class Aktarim
    {
        Genius genius;
        Mikro mikro;
        int MagazaNo;
        string SrmMerkezi;
        public bool CancelProcess { get; set; }


        public Aktarim()
        {
            genius = new Genius();
            mikro = new Mikro();
            MagazaNo = Program.Session[Settings.MagazaNo].ToString().ToInt();
            SrmMerkezi = Program.Session[Settings.SrmMerkezi].ToString();
        }

        public Tuple<bool, bool> LisansControl(int programID)
        {
            Stream str = Assembly.GetAssembly(this.GetType()).GetManifestResourceStream("SatisAktarim.Resources.LicenseTools.dll");
            byte[] data = new BinaryReader(str).ReadBytes((int)str.Length);
            Assembly testAssembly = Assembly.Load(data);
            Type calcType = testAssembly.GetType("LicenseTools.LicenseMgr");
            object calcInstance = Activator.CreateInstance(calcType, new object[] { programID });
            bool[] sonuc = (bool[])calcType.InvokeMember("Check", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, calcInstance, null);
            return new Tuple<bool, bool>(sonuc[0], sonuc[1]);
        }

        public void Start(DateTime tarih)
        {
            try
            {
                CancelProcess = false;
                List<Document> docs = genius.SatisBilgisi(tarih);
                using (SqlConnection cn = new SqlConnection(this.ConnectionString))
                {
                    cn.Open();
                    SqlTransaction trn = cn.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
                    using (DataEntities ent = new DataEntities())
                    {
                        string evrakSeri = "";
                        int evrakSira = 0;
                        int evrakSatir = mikro.MaxEvrakSatir(EvrakTipleri.PerakendeSatisIrsaliyesi, EvrakSeri(false), Convert.ToInt32(tarih.Year.ToString() + tarih.Month.ToString("00") + tarih.Day.ToString("00")), this.ConnectionString);
                        foreach (Document doc in docs.Where(x => x.Gecerli == 0))
                        {
                            if (CancelProcess)
                                return;

                            if (Program.Session[Settings.CariliAyriSatis].ToString() == "Evet")
                            {
                                if (!string.IsNullOrEmpty(doc.MusteriNo))
                                {
                                    evrakSeri = EvrakSeri(true);
                                    evrakSira = mikro.MaxEvrakNo(EvrakTipleri.PerakendeSatisIrsaliyesi, evrakSeri, Convert.ToInt32(tarih.Year.ToString().Substring(2) + tarih.Month.ToString("00") + tarih.Day.ToString("00") + "000"), this.ConnectionString);
                                    int satir = 0;
                                    mikro.SharEkle(doc, trn, evrakSeri, evrakSira, ref satir, SrmMerkezi, MagazaNo);
                                }
                                else
                                {
                                    evrakSeri = EvrakSeri(false);
                                    evrakSira = Convert.ToInt32(tarih.Year.ToString() + tarih.Month.ToString("00") + tarih.Day.ToString("00"));
                                    mikro.SharEkle(doc, trn, evrakSeri, evrakSira, ref evrakSatir, SrmMerkezi, MagazaNo);
                                }
                            }
                            else
                            {
                                evrakSeri = EvrakSeri(false);
                                evrakSira = Convert.ToInt32(tarih.Year.ToString() + tarih.Month.ToString("00") + tarih.Day.ToString("00"));
                                mikro.SharEkle(doc, trn, evrakSeri, evrakSira, ref evrakSatir, SrmMerkezi, MagazaNo);
                            }

                            string cl = doc.GenerateClosureID();
                            ent.AddToEvraklar(new Evrak { ClosureID = cl, Tarih = doc.Tarih });
                        }

                        try
                        {
                            if (!CancelProcess)
                            {
                                trn.Commit();
                                ent.SaveChanges();
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Windows.Forms.MessageBox.Show(ex.Message);
                            if (ex.InnerException != null)
                                System.Windows.Forms.MessageBox.Show(ex.InnerException.Message);
                        }
                        finally
                        {
                            cn.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                if (ex.InnerException != null)
                    System.Windows.Forms.MessageBox.Show(ex.InnerException.Message);
            }
        }

        public void YenidenAktar(DateTime tarih)
        {
            CancelProcess = false;
            using (SqlConnection cn = new SqlConnection(this.ConnectionString))
            {
                cn.Open();
                SqlTransaction trn = cn.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
                int sira = Convert.ToInt32(tarih.Year.ToString() + tarih.Month.ToString("00") + tarih.Day.ToString("00"));
                mikro.EvrakSil(EvrakSeri(false), sira, sira, trn);
                sira = Convert.ToInt32(tarih.Year.ToString().Substring(2) + tarih.Month.ToString("00") + tarih.Day.ToString("00") + "000");
                int bit = Convert.ToInt32(tarih.Year.ToString().Substring(2) + tarih.Month.ToString("00") + tarih.Day.ToString("00") + "999");
                mikro.EvrakSil(EvrakSeri(true), sira, bit, trn);

                using (DataEntities ent = new DataEntities())
                {
                    var satislar = ent.Evraklar.Where(x => x.Tarih == tarih).ToList();
                    foreach (var item in satislar)
                    {
                        if (CancelProcess)
                            return;
                        ent.DeleteObject(item);
                    }
                    try
                    {
                        if (!CancelProcess)
                        {
                            trn.Commit();
                            ent.SaveChanges();
                        }
                    }
                    catch (Exception)
                    {

                    }
                    finally
                    {
                        cn.Close();
                    }
                }
            }
        }

        private string EvrakSeri(bool cari)
        {
            if (cari)
                return "CR" + MagazaNo.ToString("00");
            else
                return "ON" + MagazaNo.ToString("00");
        }

        public string ConnectionString
        {
            get
            {
                string serverName = Program.Session[Settings.ServerName].ToString();
                string databaseName = Program.Session[Settings.DatabaseName].ToString();
                SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
                sqlBuilder.DataSource = serverName;
                sqlBuilder.InitialCatalog = databaseName;
                sqlBuilder.MultipleActiveResultSets = true;
                if (Program.Session[Settings.AuthenticateMode].ToString() == "Sql")
                {
                    sqlBuilder.UserID = Program.Session[Settings.UserName].ToString();
                    sqlBuilder.Password = Program.Session[Settings.Password].ToString();
                    sqlBuilder.IntegratedSecurity = false;
                }
                else
                    sqlBuilder.IntegratedSecurity = true;

                return sqlBuilder.ToString();
            }
        }
    }
}
